package com.bdqn.t330.ch05.aop;

import org.aopalliance.intercept.Joinpoint;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;

import java.util.Arrays;

public class UserServiceLogger {

    private Logger logger = Logger.getLogger(UserServiceLogger.class);

    /**
     * 前置增强
     *
     * @param joinPoint
     */
    public void before1111(JoinPoint joinPoint) {
        logger.info("调用:" + joinPoint.getTarget() +
                "的" + joinPoint.getSignature().getName() + "方法.方法入参:" + Arrays.toString(joinPoint.getArgs()));
    }

    /**
     * 后置增强
     *
     * @param joinPoint
     * @param result
     */
    public void afterReturning(JoinPoint joinPoint, Object result) {
        logger.info("调用" + joinPoint.getTarget() + "的" + joinPoint.getSignature().getName() + "方法.方法返回值:" + result);
    }

    /**
     * 最终增强
     *
     * @param joinpoint
     */
    public void afterLogger(JoinPoint joinpoint) {
        logger.info(joinpoint.getSignature().getName() + "方法执行结束.");
    }

    /**
     * 异常增强
     *
     * @param joinPoint
     * @param exception
     */
    public void afterThrowing(JoinPoint joinPoint, RuntimeException exception) {
        logger.error(joinPoint.getSignature().getName() + "发生异常!" + exception);
    }

    /**
     * 环绕增强
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    public Object aroundLogger(ProceedingJoinPoint joinPoint) throws Throwable {
        logger.info("调用:" + joinPoint.getTarget() +
                "的" + joinPoint.getSignature().getName() + "方法.方法入参:" + Arrays.toString(joinPoint.getArgs()));
        try {
            //执行实际的业务方法
            Object object = joinPoint.proceed();
            logger.info("调用" + joinPoint.getTarget() + "的" + joinPoint.getSignature().getName() + "方法.方法返回值:" + object);
            return object;
        } catch (Throwable throwable) {
            logger.error(joinPoint.getSignature().getName() + "发生异常!" + throwable);
            throw throwable;
        } finally {
            logger.info(joinPoint.getSignature().getName() + "方法执行结束.");
        }
    }
}
